import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/pages/navbar/child/video_list.dart';

class VideoPage extends StatefulWidget {
  const VideoPage({super.key});

  @override
  State<VideoPage> createState() => _VideoPageState();
}

// ignore: camel_case_types
class video {
  // ignore: prefer_typing_uninitialized_variables
  var url;
  // ignore: prefer_typing_uninitialized_variables
  var img;
  // ignore: prefer_typing_uninitialized_variables
  var title;
  video(this.url, this.img, this.title);
}

class _VideoPageState extends State<VideoPage>
    with AutomaticKeepAliveClientMixin {
  List<video> videos = [];
  bool loading = false;
  ScrollController controller = ScrollController();

  void getVideo() async {
    setState(() {
      loading = true;
    });
    if (!mounted) return;
    for (var i = 0; i < 10; i++) {
      Response res = await randomVideo();
      if (res.data['code'] != 200) continue;
      setState(() {
        videos.add(video(res.data['download_url'], res.data['image_url'],
            res.data['video_title']));
      });
    }
    setState(() {
      loading = false;
    });
  }

  @override
  void initState() {
    super.initState();
    getVideo();
    // 滚动到底部时加载更多
    controller.addListener(() {
      if (controller.position.pixels == controller.position.maxScrollExtent) {
        getVideo();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '视频',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        toolbarHeight: 40,
        elevation: 0,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        surfaceTintColor: Theme.of(context).colorScheme.primaryContainer,
        actions: [
          Icon(
            Icons.video_library,
            color: Theme.of(context).colorScheme.primary,
          ),
          const SizedBox(width: 10),
        ],
      ),
      // 下拉刷新
      body: RefreshIndicator(
        onRefresh: () async {
          setState(() {
            videos = [];
          });
          getVideo();
        },
        child: Container(
          margin: EdgeInsets.all(5),
          child: buildVideoList(),
        ),
      ),
    );
  }

  Widget buildVideoList() {
    return GridView.builder(
      controller: controller,
      itemCount: videos.length + 1,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 5,
        crossAxisSpacing: 5,
        childAspectRatio: 0.6,
      ),
      itemBuilder: (context, index) {
        // 如果到达最后一个项，显示加载动画
        if (index == videos.length) {
          return loading
              ? Container(
                  decoration: BoxDecoration(
                    // 圆角
                    borderRadius: BorderRadius.circular(10),
                    // 阴影
                    boxShadow: [
                      BoxShadow(
                        color: Theme.of(context)
                            .colorScheme
                            .onSurface
                            // ignore: deprecated_member_use
                            .withOpacity(0.1),
                        spreadRadius: 1,
                        blurRadius: 2,
                        offset: Offset(1, 2),
                      ),
                    ],
                  ),
                  child: Center(
                    child: CircularProgressIndicator(),
                  ),
                )
              : null;
        } else {
          return GestureDetector(
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => VideoList(
                        videoUrl: videos[index].url.toString(),
                        videoTitle: videos[index].title.toString()),
                  ));
            },
            child: Container(
              decoration: BoxDecoration(
                color: Colors.black,
                // 圆角
                borderRadius: BorderRadius.circular(10),
                // 阴影
                boxShadow: [
                  BoxShadow(
                    color: Theme.of(context)
                        .colorScheme
                        .onSurface
                        // ignore: deprecated_member_use
                        .withOpacity(0.1),
                    spreadRadius: 1,
                    blurRadius: 2,
                    offset: Offset(1, 2),
                  ),
                ],
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Stack(
                  alignment: Alignment.bottomCenter,
                  children: [
                    Center(
                      child: Image.network(videos[index].img.toString(),
                          fit: BoxFit.cover),
                    ),
                    Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.bottomLeft,
                      // tags信息
                      child: Text(
                        videos[index].title.toString(),
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        }
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}
